package com.smartwasser.yunhtgl.apphtgl.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.smartwasser.yunhtgl.apphtgl.App;
import com.smartwasser.yunhtgl.apphtgl.R;
import com.smartwasser.yunhtgl.apphtgl.adapter.CaseAdapter02;
import com.smartwasser.yunhtgl.apphtgl.base.BaseActivity;
import com.smartwasser.yunhtgl.apphtgl.base.BaseConstant;
import com.smartwasser.yunhtgl.apphtgl.base.BaseSpinner;
import com.smartwasser.yunhtgl.apphtgl.bean.CaseProcess2Bean;
import com.smartwasser.yunhtgl.apphtgl.bean.CaseProcess2Bean.ListBean;
import com.smartwasser.yunhtgl.apphtgl.bean.CompanyBean;
import com.smartwasser.yunhtgl.apphtgl.presenter.CaseProcess2Presenter;
import com.smartwasser.yunhtgl.apphtgl.presenter.CaseProcess2PresenterImpl;
import com.smartwasser.yunhtgl.apphtgl.tree.Dept;
import com.smartwasser.yunhtgl.apphtgl.tree.Node;
import com.smartwasser.yunhtgl.apphtgl.tree.NodeHelper;
import com.smartwasser.yunhtgl.apphtgl.tree.NodeTreeAdapter;
import com.smartwasser.yunhtgl.apphtgl.view.CaseProcess2View;
import com.smartwasser.yunhtgl.apphtgl.utils.ACache;
import com.smartwasser.yunhtgl.apphtgl.utils.Logger;
import com.smartwasser.yunhtgl.apphtgl.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.View.inflate;
import static com.dou361.dialogui.DialogUIUtils.dismiss;
import static com.smartwasser.yunhtgl.apphtgl.utils.SharedUtils.getStringData;

/**
 * 已完成合同备案
 */
public class CaseProcess2 extends BaseActivity implements CaseProcess2View {
    private CaseProcess2Presenter caseProcess2Presenter = new CaseProcess2PresenterImpl(this);
    private List<ListBean> mList = new ArrayList<>();
    private Boolean getCom = false, getMessage = false;
    private String year = "", season = "";
    private CaseAdapter02 mAdapter;
    private CompanyBean companyBean;
    private Dialog loadingHorizontal;
    private String currentId;
    private ACache aCache;
    @BindView(R.id.tv_toolbar)
    TextView tv_toolbar;
    @BindView(R.id.toolbar_what)
    TextView toolbar_what;
    @BindView(R.id.swipeRefresh)
    RefreshLayout swipeRefresh;
    @BindView(R.id.sp_list)
    ListView sp_list;
    @BindView(R.id.all_com)
    LinearLayout all_com;
    @BindView(R.id.finish1)
    TextView finish1;
    @BindView(R.id.finish2)
    Spinner finish2;
    @BindView(R.id.finish3)
    Spinner finish3;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_case_process2);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
    }

    @Override
    public void initView() {
        tv_toolbar.setText("已完成合同备案");
        initSpinner();
        initRecyclerView();
    }

    @Override
    public void initData() {
        loadingHorizontal = showLoadingHorizontal(this, "加载中...").show();
        try {
            caseProcess2Presenter.getMessages(getStringData(this, "JSESSIONID", ""), null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != aCache.getAsObject("mLinkedList")) {
            Logger.e("有缓存，读取缓存");
            getCom = true;
            mLinkedList = (LinkedList<Node>) aCache.getAsObject("mLinkedList");
        } else {
            Logger.e("没有缓存，请求网络");
            try {
                caseProcess2Presenter.getCompany(getStringData(this, "JSESSIONID", ""));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.back, R.id.all_com})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.all_com:
                showPopupWindow(all_com);
                break;
        }
    }

    private void getMessagesData(String com) {
        try {
            Logger.e("JSESSIONID = " + getStringData(this, "JSESSIONID", ""));
            Logger.e("year = " + year);
            Logger.e("season = " + season);
            Logger.e("com = " + com);
            caseProcess2Presenter.getMessages(getStringData(this, "JSESSIONID", ""), year, season, com);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void success(CaseProcess2Bean caseProcessBean) {
        if (!getMessage) {
            getMessage = true;
        }
        if (getMessage && getCom && loadingHorizontal.isShowing()) {
            dismiss(loadingHorizontal);
        }
        if (swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
        this.mList = caseProcessBean.getList();
        mAdapter.refresh(mList);
    }

    @Override
    public void successCompany(CompanyBean companyBean) {
        this.companyBean = companyBean;
        new Thread() {
            @Override
            public void run() {
                Logger.e("successCompany");
                data = new ArrayList<>();
                addOne(data);
                mLinkedList.addAll(NodeHelper.sortNodes(data));
                if (!getCom) {
                    getCom = true;
                }
                aCache.put("mLinkedList", mLinkedList, BaseConstant.TIME_HOUR);
                if (getMessage && getCom && loadingHorizontal.isShowing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismiss(loadingHorizontal);
                        }
                    });
                }
            }
        }.start();
    }

    @Override
    public void error() {
        dismiss(loadingHorizontal);
        showError();
    }

    private void initRecyclerView() {
        mAdapter = new CaseAdapter02(this, mList);
        sp_list.setAdapter(mAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != mList && mList.size() > 0) {
                            mList.clear();
                            App.getInstance().getCaseProcess1List().clear();
                            mAdapter.refresh(mList);
                        }
                        Logger.e("id = " + currentId);
                        if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                            getMessagesData(currentId);
                        } else {
                            getMessagesData(null);
                        }
                    }
                }, 500);
            }
        });
        sp_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(CaseProcess2.this, CaseCensorActivity.class);
                intent.putExtra("type", "finish");
                intent.putExtra("id", mList.get(position).getId());
                startActivity(intent);
            }
        });
    }


    private void initSpinner() {
        final List<String> arrayList2 = new ArrayList<>();
        arrayList2.add("全部时间");
        arrayList2.add("2018");
        arrayList2.add("2017");
        arrayList2.add("2016");
        final List<String> arrayList3 = new ArrayList<>();
        arrayList3.add("全部月度");
        arrayList3.add("第1月度");
        arrayList3.add("第2月度");
        arrayList3.add("第3月度");
        arrayList3.add("第4月度");
        arrayList3.add("第5月度");
        arrayList3.add("第6月度");
        arrayList3.add("第7月度");
        arrayList3.add("第8月度");
        arrayList3.add("第9月度");
        arrayList3.add("第10月度");
        arrayList3.add("第11月度");
        arrayList3.add("第12月度");

        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
                R.layout.spinner_drop, arrayList2) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = inflate(getContext(), R.layout.spinner_item_layout, null);
                TextView label = view.findViewById(R.id.spinner_item_label);
                label.setText(arrayList2.get(position));
                if (finish2.getSelectedItemPosition() == position) {
                    label.setTextColor(getResources().getColor(R.color.colorTitle));
                } else {
                    label.setTextColor(getResources().getColor(R.color.colorText));
                }
                return view;
            }

        };
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this,
                R.layout.spinner_drop, arrayList3) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = inflate(getContext(), R.layout.spinner_item_layout, null);
                TextView label = view.findViewById(R.id.spinner_item_label);
                label.setText(arrayList3.get(position));
                if (finish3.getSelectedItemPosition() == position) {
                    label.setTextColor(getResources().getColor(R.color.colorTitle));
                } else {
                    label.setTextColor(getResources().getColor(R.color.colorText));
                }
                return view;
            }
        };
        adapter2.setDropDownViewResource(R.layout.spinner_item_layout);
        adapter3.setDropDownViewResource(R.layout.spinner_item_layout);
        finish2.setAdapter(adapter2);
        finish3.setAdapter(adapter3);
        finish2.setSelection(0, true);
        finish3.setSelection(0, true);
        finish2.setOnItemSelectedListener(new BaseSpinner() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadingHorizontal = showLoadingHorizontal(getApplication(), "正在加载...").show();
                if (i == 0) {
                    year = "";
                } else if (i == 1) {
                    year = "2018";
                } else if (i == 2) {
                    year = "2017";
                } else if (i == 3) {
                    year = "2016";
                }
                if (null != mList && mList.size() > 0) {
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                }
                if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                    Logger.e("getData(id)");
                    getMessagesData(currentId);
                } else {
                    getMessagesData(null);
                    Logger.e("getData(null)");
                }
            }

        });
        finish3.setOnItemSelectedListener(new BaseSpinner() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadingHorizontal = showLoadingHorizontal(getApplication(), "正在加载...").show();
                if (i == 0) {
                    season = "";
                } else if (i == 1) {
                    season = "1";
                } else if (i == 2) {
                    season = "2";
                } else if (i == 3) {
                    season = "3";
                } else if (i == 3) {
                    season = "4";
                }
                if (null != mList && mList.size() > 0) {
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                }
                if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                    getMessagesData(currentId);
                } else {
                    getMessagesData(null);
                }
            }

        });
    }

    private PopupWindow popupWindow;
    private LinkedList<Node> mLinkedList = new LinkedList<>();
    private NodeTreeAdapter nodeTreeAdapter;
    private List<Node> data;

    private void showPopupWindow(View view) {
        if (null != mLinkedList) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.pop_window, null);
            ListView pop_list = contentView.findViewById(R.id.pop_list);
            final TextView pop_name = contentView.findViewById(R.id.pop_name);
            pop_name.setText("当前选择 : " + finish1.getText());
            nodeTreeAdapter = new NodeTreeAdapter(this, pop_list, mLinkedList);
            pop_list.setAdapter(nodeTreeAdapter);
            nodeTreeAdapter.setOnItemClickListener(new NodeTreeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, String id, String name) {
                    currentId = id;
                    if (name.equals("全部单位")) {
                        getMessagesData(null);
                    } else {
                        getMessagesData(id);
                    }
                    finish1.setText(name);
                    if (null != popupWindow) {
                        popupWindow.dismiss();
                    }
                }
            });
            nodeTreeAdapter.notifyDataSetChanged();
            popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.showAsDropDown(view);
        }
    }

    private void addOne(List<Node> data) {
        if (null != companyBean && companyBean.getVo().size() > 0) {
            data.add(new Dept(-1, -1, "全部单位", "全部单位"));
            for (int i = 0; i < companyBean.getVo().size(); i++) {
                Logger.e("i = " + i);
                try {
                    int id = Integer.parseInt(companyBean.getVo().get(i).getId());
                    int pid = Integer.parseInt(companyBean.getVo().get(i).getPId());
                    String name = companyBean.getVo().get(i).getName();
                    String mId = companyBean.getVo().get(i).getId();
                    data.add(new Dept(id, pid, name, mId));
                } catch (Exception e) {
                    Logger.e("exception");
                }
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    break;
            }
        }
    };
}